const {
// addLessLoader,
override,
//·addBabelPlugin,
overrideDevServer,
setWebpackPublicPath,
// addWebpackAlias,
} = require('customize-cra');
const { merge } = require('webpack-merge');
const mockApi = require('./mock');

// const envConfigVariables = require('./env_config');
// const { addwebpackEnvPrefix } = require('./env_config/uti1s/index.js');

let routerBasePath = '/'; // dev.default·is '/',when prod is like·'/project1'
let publicPath = '/';
if (process.env.NODE_ENV === 'development') {
  process.env.PORT = 5555;
} else {
  routerBasePath = process.env.PUBLIC_URL || '/'; // dev.default·is '/',when prod is like·'/project1'
  publicPath = process.env.PUBLIC_URL || '/';
}

const envGlobal = {
  REGION: JSON.stringify(process.env.REGION),
  ROUTER_BASE_PATH: JSON.stringify(routerBasePath),
  //·...envConfigVariables,
  CLIENT_SECRET: JSON.stringify(process.env.CLIENT_SECRET),
  COMMIT_ID: JSON.stringify(process.env.COMMIT_ID),
  BRANCH_NAME: JSON.stringify(process.env.BRANCH_NAME),
  BUILD_DATE: JSON.stringify(process.env.BUILD_DATE),
  CONMIT_TAG: JSON.stringify(process.env.COMMIT_TAG),
}

//·DIY CRA-override fn:
const findMebpackPlugin = (plugins, pluginName) => plugins.find((plugin) => plugin.constructor.name === pluginName);
const overrideProcessEnv = (value) => (config) => {
  const plugin = findMebpackPlugin(config.plugins, 'DefinePlugin');
  const processEnv = plugin.definitions['process.env'] || {};
  plugin.definitions['process.env'] = {
    ...processEnv,
    ...value
  };
  return config;
}

const overrideTenserOptions = (_value) => (config) => {
  const tenserOptions = config.optimization.minimizer[0].options;
  if (process.env.HSBC_ENV === 'prd' && tenserOptions) {
    tenserOptions.terserOptions = merge(tenserOptions.terserOptions, {
      compress: { drop_console:true },
    })
  }
  // to remove-console.log·code
 return config;
};

const addProxy = (proxy) => (config) => {
  // eslint-disable-next-line no-param-reassign
  config.proxy = proxy;
  if (process.env.MOCK === 'mock') {
    //·eslint-disable-next-line no-param-reassign
    config.before = (app) => { mockApi(app); }
  }
  return config;
}

const localBackendServerUr1 = `$envConfigVariables.URL/api-staff`;

const devServeConfig = overrideDevServer(
  addProxy({
    'share-blotter-service': {
      target: localBackendServerUr1,
      secure: false,
    }
  }),
);

const webpackConfig = override(
  setWebpackPublicPath(publicPath),
  overrideProcessEnv(envGlobal),
  overrideTenserOptions(),
);

/* config-overrides.js*/
module.exports = {
  webpack: webpackConfig,
  devServer: devServeConfig,
}